package examples;

import com.jingdong.api.JingdongApiSDK;
import com.jingdong.api.model.*;

import java.util.*;

/**
 * 京东配送API SDK Java使用示例
 *
 * @author 林生
 * @version 1.0.0
 */
public class ApiExample {
    
    public static void main(String[] args) {
        System.out.println("=== 京东配送API SDK Java示例 ===\n");
        
        // 配置SDK
        ApiConfig config = ApiConfig.builder()
                .appKey("your_app_key")
                .appSecret("your_app_secret")
                .merchantNo("your_merchant_no")
                .sandboxMode(true) // 测试环境
                .timeout(30)
                .enableLog(true)
                .build();
        
        JingdongApiSDK sdk = new JingdongApiSDK(config);
        
        try {
            // 1. 测试连接
            System.out.println("1. 测试API连接...");
            ApiResult result = sdk.testConnection();
            if (result.isSuccess()) {
                System.out.println("✓ API连接正常");
            } else {
                System.out.println("✗ API连接失败: " + result.getMessage());
            }
            System.out.println();
            
            // 2. 申请成为配送商
            System.out.println("2. 申请成为配送商...");
            MerchantInfo merchantInfo = MerchantInfo.builder()
                    .merchantName("测试商户")
                    .merchantPhone("13800138000")
                    .merchantAddress("北京市朝阳区测试地址")
                    .businessLicense("91110000000000000X")
                    .contactPerson("张三")
                    .contactPhone("13800138001")
                    .merchantType("1")
                    .build();
            
            result = sdk.applyMerchant(merchantInfo);
            if (result.isSuccess()) {
                System.out.println("✓ 申请提交成功");
                System.out.println("申请ID: " + 
                        (result.getData() != null ? result.getData().get("apply_id") : "N/A"));
            } else {
                System.out.println("✗ 申请失败: " + result.getMessage());
            }
            System.out.println();
            
            // 3. 查询配送商状态
            System.out.println("3. 查询配送商状态...");
            result = sdk.queryMerchantStatus();
            if (result.isSuccess()) {
                System.out.println("✓ 查询成功");
                System.out.println("状态: " + 
                        (result.getData() != null ? result.getData().get("status") : "N/A"));
            } else {
                System.out.println("✗ 查询失败: " + result.getMessage());
            }
            System.out.println();
            
            // 4. 预下单（获取运费）
            System.out.println("4. 预下单获取运费...");
            Map<String, Object> preOrderData = new HashMap<>();
            preOrderData.put("cargo_type", "1");
            preOrderData.put("cargo_weight", 1000); // 1kg
            preOrderData.put("cargo_num", "1");
            preOrderData.put("cargo_price", "100.00");
            
            Map<String, Object> pickupInfo = new HashMap<>();
            pickupInfo.put("address", "北京市朝阳区发货地址");
            pickupInfo.put("lng", 116.397470);
            pickupInfo.put("lat", 39.908860);
            preOrderData.put("pickup_info", pickupInfo);
            
            Map<String, Object> deliveryInfo = new HashMap<>();
            deliveryInfo.put("address", "北京市海淀区收货地址");
            deliveryInfo.put("lng", 116.307490);
            deliveryInfo.put("lat", 39.981730);
            preOrderData.put("delivery_info", deliveryInfo);
            
            long currentTime = System.currentTimeMillis() / 1000;
            preOrderData.put("expected_pickup_time", currentTime + 3600); // 1小时后取货
            preOrderData.put("expected_delivery_time", currentTime + 7200); // 2小时后送达
            
            result = sdk.preOrder(preOrderData);
            if (result.isSuccess()) {
                System.out.println("✓ 询价成功");
                System.out.println("配送费: " + 
                        (result.getData() != null ? result.getData().get("delivery_fee") : "N/A") + " 元");
            } else {
                System.out.println("✗ 询价失败: " + result.getMessage());
            }
            System.out.println();
            
            // 5. 创建配送订单
            System.out.println("5. 创建配送订单...");
            OrderData orderData = OrderData.builder()
                    .orderId("TEST_ORDER_" + System.currentTimeMillis())
                    .tradeOrderSource(1)
                    .serviceCode("STANDARD")
                    .recipientName("李四")
                    .recipientPhone("13900139000")
                    .recipientAddress("北京市海淀区收货地址123号")
                    .recipientLng(116.307490)
                    .recipientLat(39.981730)
                    .prebook(0)
                    .totalWeight(1.0) // 1kg
                    .senderLng(116.397470)
                    .senderLat(39.908860)
                    .senderName("王五")
                    .senderPhone("13800138000")
                    .senderAddress("北京市朝阳区发货地址456号")
                    .operatorName("王五")
                    .orderRemark("测试订单备注")
                    .shopRemark("商户备注信息")
                    .build();
            
            // 设置扩展信息
            Map<String, Object> extInfo = new HashMap<>();
            extInfo.put("remark", "测试订单，请小心配送");
            orderData.setExtInfo(extInfo);
            
            result = sdk.createOrder(orderData);
            String jdOrderId = null;
            if (result.isSuccess()) {
                System.out.println("✓ 订单创建成功");
                jdOrderId = result.getData() != null ? 
                        (String) result.getData().get("jd_order_id") : null;
                System.out.println("京东订单号: " + (jdOrderId != null ? jdOrderId : "N/A"));
            } else {
                System.out.println("✗ 订单创建失败: " + result.getMessage());
            }
            System.out.println();
            
            // 6. 查询订单状态
            if (jdOrderId != null) {
                System.out.println("6. 查询订单状态...");
                result = sdk.queryOrder(orderData.getOrderId(), jdOrderId);
                if (result.isSuccess()) {
                    System.out.println("✓ 查询成功");
                    System.out.println("订单状态: " + 
                            (result.getData() != null ? result.getData().get("status") : "N/A"));
                    System.out.println("骑手信息: " + 
                            (result.getData() != null ? result.getData().get("rider_name") : "N/A"));
                } else {
                    System.out.println("✗ 查询失败: " + result.getMessage());
                }
                System.out.println();
                
                // 7. 查询骑手位置
                System.out.println("7. 查询骑手位置...");
                result = sdk.queryRiderLocation(orderData.getOrderId());
                if (result.isSuccess()) {
                    System.out.println("✓ 查询成功");
                    if (result.getData() != null) {
                        System.out.println("骑手位置: " + 
                                result.getData().get("rider_lng") + ", " + 
                                result.getData().get("rider_lat"));
                    }
                } else {
                    System.out.println("✗ 查询失败: " + result.getMessage());
                }
                System.out.println();
            }
            
            // 8. 查询可配送范围
            System.out.println("8. 查询可配送范围...");
            result = sdk.queryServiceArea("116.397470", "39.908860");
            if (result.isSuccess()) {
                System.out.println("✓ 查询成功");
                Boolean deliverable = result.getData() != null ? 
                        (Boolean) result.getData().get("deliverable") : null;
                System.out.println("可配送: " + (deliverable != null && deliverable ? "是" : "否"));
            } else {
                System.out.println("✗ 查询失败: " + result.getMessage());
            }
            System.out.println();
            
            // 9. 查询历史订单列表
            System.out.println("9. 查询历史订单列表...");
            Map<String, Object> condition = new HashMap<>();
            condition.put("page_size", 10);
            condition.put("page_no", 1);
            condition.put("start_time", "2023-01-01 00:00:00");
            condition.put("end_time", "2023-12-31 23:59:59");
            
            result = sdk.queryOrderList(condition);
            if (result.isSuccess()) {
                System.out.println("✓ 查询成功");
                if (result.getData() != null && result.getData().get("orders") != null) {
                    @SuppressWarnings("unchecked")
                    List<Map<String, Object>> orders = (List<Map<String, Object>>) result.getData().get("orders");
                    System.out.println("订单数量: " + orders.size());
                } else {
                    System.out.println("订单数量: 0");
                }
            } else {
                System.out.println("✗ 查询失败: " + result.getMessage());
            }
            System.out.println();
            
            // 10. 验证回调签名（示例）
            System.out.println("10. 验证回调签名...");
            Map<String, Object> callbackData = new HashMap<>();
            callbackData.put("out_order_id", "TEST_ORDER_123456");
            callbackData.put("jd_order_id", "JD_123456789");
            callbackData.put("order_status", "20");
            callbackData.put("rider_name", "配送员张三");
            callbackData.put("rider_phone", "13700137000");
            
            // 生成签名进行验证
            String testSignature = "test_signature_here";
            boolean isValid = sdk.verifyCallback(callbackData, testSignature);
            System.out.println(isValid ? "✓ 签名验证通过" : "✗ 签名验证失败");
            System.out.println();
            
        } catch (Exception e) {
            System.err.println("示例执行异常: " + e.getMessage());
            e.printStackTrace();
        } finally {
            // 关闭资源
            sdk.close();
        }
        
        System.out.println("=== 示例执行完成 ===");
    }
}
